package com.example.httprequest;



import com.alibaba.fastjson.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 使用okhttp封装的http请求工具，需要网络权限，需要在
 */
public class HttpUtil {


    private static final String DEVICE = "ANDROID";

    private static final String URL_PREFIX = "http://localhost:8080";

    private static final Long TIMEOUT = 5 * 1000L;

    private static String token = "ttttooookkkkeeeennnn";


    /**
     * 异步get
     * @param url
     * @param callBack
     */
    public static void getAsync(String url, ResponseCallBack callBack) {
        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request
                .Builder()
                .addHeader("token", token)
                .addHeader("device", DEVICE)
                .url(url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onException(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                callBack.onSuccess(res);

            }
        });

    }

    public static void postAsync(String url, Object object, Callback callback) {
        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .build();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), JSON.toJSONString(object));

        Request request = new Request
                .Builder()
                .addHeader("token", token)
                .addHeader("device", DEVICE)
                .url(url)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(callback);
    }

}
